﻿var formidable = require('formidable');
var node_xlsx = require('node-xlsx');
var fs = require('fs');
var path = require('path');
var nodemailer = require('nodemailer')
var smtpTransport = require('nodemailer-smtp-transport');
var config = require('../config.json')
var smtpTransport = nodemailer.createTransport(smtpTransport({
    host: config.email.service,
    secureConnection: true, // use SSL
    port: 465,
    //secure: false, // secure:true for port 465, secure:false for port 587
    auth: {
        user: config.email.user,
        pass: config.email.pass
    }
}));

exports.upload = function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    var fileTypeError = false;
    var target_path = path.resolve(__dirname, "../upload");
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;
    form.maxFieldsSize = 10 * 1024 * 1024;
    form.uploadDir = target_path;
    var fields = [];
    var files = [];
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log('文件上传错误！');
            return;
        }
        var filename = files.file.name;
        // 对文件名进行处理，以应对上传同名文件的情况  
        var nameArray = filename.split('.');
        var type = nameArray[nameArray.length - 1];
        var name = '';
        for (var i = 0; i < nameArray.length - 1; i++) {
            name = name + nameArray[i];
        }

        var date = new Date();
        var time = '/jz-' + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getHours() + "-" + date.getMinutes();
        var avatarName = time + '.' + type;

        var newPath = path.join(form.uploadDir, avatarName);
        console.log(newPath);
        fs.renameSync(files.file.path, newPath);  //重命名  
        console.log('上传成功！' + avatarName);
        var obj = xlsxTojson(newPath)
        res.send({ data: obj, filename: files.file.name })
    });
}

function xlsxTojson(newPath) {
    if (fs.existsSync(newPath)) {
        var obj = node_xlsx.parse(newPath)
        var arry_1 = [];
        for (var i in obj) {
            if (obj[i].name == 'Sheet1') {
                arry_1 = obj[i].data
            }
        }
        var len = arry_1.length;//表数据长度
        var key_arr = arry_1[0]//表头
        var arry_2 = []; //新整理数据
        for (var i = 1; i < arry_1.length; i++) {
            var person_info = []; //人员数据[{key:,value}]
            for (var k in key_arr) {
                var info = {};//数据key，value
                info.key = key_arr[k];
                info.value = arry_1[i][k] || 0;
                person_info.push(info)
            }
            arry_2.push(person_info)
        }
        return arry_2;
    }
}

/**
 * @param {String} recipient 收件人
 * @param {String} subject 发送的主题
 * @param {String} html 发送的html内容
 */
exports.sendmail = async function (message, ws) {
    var option = JSON.parse(message)
    var data = option.data_str;
    var month = option.month;
    var cnt = 0;
    for (let i in data) {
        var value = data[i]
        var recipient = ''
        var subject = ''
        var ID = 0
        var html = '<p class="MsoNormal" align="left" style="font-family:&quot;font-size:14px;background-color:#FFFFFF;"> \
                    <span>亲爱的同事：</span><span class="apple-converted-space"><span>&nbsp;</span></span> \
                    </p>\
                    <p class="MsoNormal" align="left" style="font-family:&quot;font-size:14px;background-color:#FFFFFF;">\
                        <span>&nbsp; &nbsp; &nbsp; &nbsp;工作辛苦了！</span><span class="apple-converted-space"><span>&nbsp;</span></span> \
                    </p>\
                    <p class="MsoNormal" align="left" style="font-family:&quot;font-size:14px;background-color:#FFFFFF;">\
                        <span>&nbsp; &nbsp; &nbsp; &nbsp;这个您上个月的工资信息，如有疑问，请与总经办联系。</span><span style="font-size:18pt;"></span> \
                    </p>\
                    <p class="MsoNormal" align="left" style="font-family:&quot;font-size:14px;background-color:#FFFFFF;">\
                        <span>&nbsp; &nbsp; &nbsp; &nbsp;联系电话：028-85306007</span> \
                    </p>\
                    <div align="center" style="font-family:&quot;font-size:14px;background-color:#FFFFFF;">\
                    <table class="MsoNormalTable ke-zeroborder" border="1" cellspacing="0" cellpadding="0" width="100%" style="width:1669px;">\
                    <tbody>'
        var th = '<tr>'
        var tr = '<tr>'
        for (k in value) {
            recipient = value[k].key == "邮箱" ? value[k].value : recipient;
            subject = value[k].key == "姓名" ? value[k].value : subject;
            ID = value[k].key == "序号" ? value[k].value : ID;
            if (value[k].key != "发送状态") {
                th += '<th><p><span style="font-family:&quot;font-size:12px;background-color:#FFFFFF;">' + value[k].key + '&nbsp;</span> </p></th>'
                tr += '<td><p><span style="font-family:&quot;font-size:12px;background-color:#FFFFFF;">' + value[k].value + '&nbsp;</span> </p></td>'
            }
        }
        html += th
        html += '</tr>'
        html += tr
        html += '</tr> </tbody></table></div>'
        // 
        cnt++
        var obj = {
            cnt: cnt,
            ID: ID,
            recipient: recipient,
            subject: subject,
            month: month,
            html: html
        }
        if (ws.readyState == 1) {
            await MailtoSend(ws, obj)
            // await sleep(ws, obj)
        } else {
            return
        }
    }
}

function MailtoSend(ws, obj) {
    return new Promise((resolve, reject) => {
        smtpTransport.sendMail({
            from: config.email.user,
            to: obj.recipient,
            subject: '成都九洲' + obj.month + "月工资条-" + obj.subject,
            html: obj.html
        }, (error, response) => {
            var redata = {
                cnt: obj.cnt,
                ID: obj.ID,
                msg: ""
            }
            if (error) {
                redata.msg = "发送失败"
                console.log(error)
            } else {
                redata.msg = "发送成功"
            };
            resolve();
            try {
                ws.send(JSON.stringify(redata))
            } catch (e) {
                console.log(e)
            }
            console.log(obj.ID + ' ' + obj.subject + ' ' + obj.recipient + ' ' + redata.msg)
        })
    })
}



function sleep(ws, obj) {
    return new Promise(resolve => {
        setTimeout(() => {
            var redata = {
                cnt: obj.cnt,
                ID: obj.ID,
                msg: "发送成功"
            }
            try {
                ws.send(JSON.stringify(redata))
            }
            catch (e) {
                console.log(e)
            }
            resolve()
        }, 50)
    })
}